package cn.sky.demo.utils;

import cn.sky.demo.domain.entity.Message;
import cn.sky.demo.mapper.MessageDao;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * 系统消息推送线程（处理 block数据块）
 */
public class MessageSendThread implements Runnable{
     
    private final Logger logger = LoggerFactory.getLogger(MessageSendThread.class);
 
    private Integer currentIndex;//当前索引
    private Integer rows;//处理数据条数
    private CountDownLatch doneSignal;//处理线程条数
    private Message message;//消息实体
    private MessageDao messageDao;//DAO
 
    public MessageSendThread(MessageDao messageDao, Message message, Integer currentIndex, Integer rows, CountDownLatch doneSignal) {
        this.message = message;
        this.messageDao = messageDao;
        this.currentIndex = currentIndex;
        this.rows = rows;
        this.doneSignal = doneSignal;
    }
     
     
    @Override
    public void run() {
        try {
            /**
             * ---------1.查询当前的block范围内的发送的手机号=>筛选目标客户群手机号---------
             */
            Map<String,Object> smsDataMap = filterPhones(message,currentIndex,rows);
            if(MapUtils.isEmpty(smsDataMap)|| null == smsDataMap.get("jgAlias")
                    || StringUtils.isBlank(smsDataMap.get("jgAlias").toString())){
                logger.debug("push param is null,caurse by target customers is nothing");
                throw new RuntimeException();
            }
            logger.info("type of target customers=>{}", message.getReceiverGroupType());
            logger.info(" result of filter target customers=>{}", smsDataMap);
              
            /**
             *  ---------2.批量发送消息---------
             *  TODO://((-?)\d{1,11}\,?){1,n}  n个线程分批发送
             */
            if("0".equals(message.getType())){//短信发送
                sendBatch(smsDataMap.get("phone").toString(),message);
            }
            if("1".equals(message.getType())){//APP推送
                if("0".equals(message.getMethod())){//实时发送
                    sendNormal(smsDataMap);
                }
                if("1".equals(message.getMethod())){//定时发送
                    sendDelay(smsDataMap);
                }
             }
        } catch (Exception e) {
            logger.error("send message thread exception=>{}{}{}{}",message,currentIndex,rows,e);
        }finally{
            doneSignal.countDown();//工人完成工作，计数器减一
        }
    }

    private Map<String, Object> filterPhones(Message message, Integer currentIndex, Integer rows) {
        // 示例逻辑：调用 DAO 查询符合条件的数据块（分页）
        List<Map<String, Object>> resultList = messageDao.selectTargetCustomersByBlock(
                message.getReceiverGroupType(), currentIndex, rows);

        if (resultList == null || resultList.isEmpty()) {
            return Collections.emptyMap();
        }

        StringBuilder phoneBuilder = new StringBuilder();
        StringBuilder aliasBuilder = new StringBuilder();

        for (Map<String, Object> record : resultList) {
            String phone = (String) record.get("phone");
            String jgAlias = (String) record.get("jgAlias");

            if (!StringUtils.isEmpty(phone)) {
                if (phoneBuilder.length() > 0) phoneBuilder.append(",");
                phoneBuilder.append(phone);
            }

            if (!StringUtils.isEmpty(jgAlias)) {
                if (aliasBuilder.length() > 0) aliasBuilder.append(",");
                aliasBuilder.append(jgAlias);
            }
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("phone", phoneBuilder.toString());
        resultMap.put("jgAlias", aliasBuilder.toString());

        return resultMap;
    }

    /**
     * APP实时推送
     * @param smsDataMap
     */
    private void sendNormal(Map<String,Object> smsDataMap) {
         //0为全部发送
        if("0".equals(message.getReceiverGroupType())){
            //JPushClient.appSendAll(message.getTitle(), message.getContent(), message.getId().toString(), StringUtils.isBlank(message.getLink())?"0":"1", message.getLink());
        }else{
            String[] jgAlias = smsDataMap.get("jgAlias").toString().split(",");
            for(String jgAlia:jgAlias){
              //  JPushClient.appSend(message.getTitle(), message.getContent(), jgAlia, message.getId().toString(), StringUtils.isBlank(message.getLink())?"0":"1", message.getLink());
            }
        }
    }
 
    /**
     * APP定时推送
     * @param smsDataMap
     */
    private void sendDelay(Map<String,Object> smsDataMap) {
         //0为全部发送
        if("0".equals(message.getReceiverGroupType())){
            /*JPushScheduleClient.createSingleSchedule(
                    DateUtil.formatDateToStr("yyyy-MM-dd HH:mm:ss", message.getExpectTime()),
                    message.getTitle(),
                    message.getContent(), 
                    message.getId().toString(),
                    StringUtils.isBlank(message.getLink())?"0":"1",
                    message.getLink());*/
        }else{
            String[] jgAlias = smsDataMap.get("jgAlias").toString().split(",");
            /*JPushScheduleClient.createSingleSchedule(
                    Arrays.asList(jgAlias),
                    DateUtil.formatDateToStr("yyyy-MM-dd HH:mm:ss", message.getExpectTime()),
                    message.getTitle(),
                    message.getContent(), 
                    message.getId().toString(),
                    StringUtils.isBlank(message.getLink())?"0":"1",
                    message.getLink());*/
        }
    }
 
 
     
     
    /**
     * 批量发送消息
     * @param smsDataList
     * @param message
     */
    private void sendBatch(String smsDataListStr,Message message){
        try {
            //批量发送方法使用异步发送
            if(!message.getContent().contains("退订回T")){
                message.setContent(message.getContent()+"退订回T");
            }
            SmsUtils.batchExecuteTask(smsDataListStr, message.getContent());
            //短信测试方法
            //SmsUtils.batchExecuteTask(smsDataListStr, message.getContent(),true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("批量发送消息异常=>{}{}",smsDataListStr,e);
        }
    }
     
 
}
